﻿#include "movement.h"
#include "../PlayerData/PlayerData.h"
#include "../../cs2 dumper/client_dll.hpp"
#include "../../Settings/Settings.h"
#include "../../dll_main.h"
#include "../../cs2 dumper/offsets.hpp"
#include <cmath> // 用于计算角度和向量
#include <iostream> // 添加用于调试输出的头文件
#include "../aimbot/aimbot.h"
#include "../IEngineCvar/IEngineCvar.hpp"
#include "../ESP/vision.h"
#include "../function/messagebox/messagebox.h"
#include <chrono>
#include <string>
#include "../SDK/Base.h"
#include "../vish/vs.h"
#include "../function/KEY/KEY.h"

using namespace all_settings;
#define _USE_MATH_DEFINES // 确保M_PI被定义

class Draw_SkyBox {
private:
    bool lastScopedState = false;
    bool commandExecuted = false;
    bool observerInfoPrinted = false; // 防止重复打印

public:
    void Updateg_SkyBox() {
    }
private:
};


class ThirdPersonManager {
private:
    bool lastThirdPersonState = false;
    uintptr_t localPlayerPawn = 0;
    bool bInitialized = false;

public:
    void Update(bool enable) {
        if (!all_settings::visual::ESP) return;

        // 获取本地玩家
        auto& playerDataManager = PlayerDataManager::GetInstance();
        auto localPlayer = playerDataManager.GetLocalPlayerData();

        if (!localPlayer.pawn || localPlayer.pawn == 0) {
            localPlayerPawn = 0;
            bInitialized = false;
            return;
        }

        //// 检查玩家是否存活
        //if (localPlayer.health <= 0) {
        //    if (lastThirdPersonState) {
        //        ResetThirdPerson();
        //    }
        //    return;
        //}

    //    if (enable != lastThirdPersonState || !bInitialized) {
    //        if (enable) {
    //            EnableThirdPerson(localPlayer.pawn);
    //        }
    //        else {
    //            DisableThirdPerson(localPlayer.pawn);
    //        }
    //        lastThirdPersonState = enable;
    //        bInitialized = true;
    //    }
    }

private:
    //void EnableThirdPerson(uintptr_t pawn) {
    //    printf("=== EnableThirdPerson Start ===\n");
    //    printf("Pawn address: 0x%p\n", (void*)pawn);

    //    // 检查CVar系统是否初始化
    //    if (!main::CVar) {
    //        printf("[ERROR] CVar system is not initialized!\n");
    //        return;
    //    }
    //    printf("[DEBUG] CVar system initialized: 0x%p\n", (void*)main::CVar);

    //    // 使用I::CVar设置第三人称
    //    IConVar* sv_cheats = main::CVar->FindVar("sv_cheats");
    //    IConVar* thirdperson = main::CVar->FindVar("thirdperson");


    //    if (sv_cheats) {
    //        printf("[DEBUG] Before - sv_cheats: %d\n", sv_cheats->GetInt());
    //        sv_cheats->SetValue(1);
    //        printf("[DEBUG] After - sv_cheats: %d\n", sv_cheats->GetInt());
    //    }

    //    if (thirdperson) {
    //        printf("[DEBUG] Before - thirdperson: %d\n", thirdperson->GetInt());
    //        thirdperson->SetValue(1);
    //        printf("[DEBUG] After - thirdperson: %d\n", thirdperson->GetInt());
    //    }


    //    printf("=== EnableThirdPerson End ===\n\n");
    //}
    //void DisableThirdPerson(uintptr_t pawn) {
    //    IConVar* thirdperson = main::CVar->FindVar("thirdperson");

    //    if (thirdperson) {
    //        thirdperson->SetValue(0); // 禁用第三人称
    //    }

    //}
    //void ResetThirdPerson() {
    //    if (localPlayerPawn) {
    //        DisableThirdPerson(localPlayerPawn);
    //    }
    //    lastThirdPersonState = false;
    //    bInitialized = false;
    //}
};



static Vector3 g_prevViewAngles;
static bool g_firstRun = true;
const float ANGLE_CHANGE_THRESHOLD = 0.5f; // 角度变化阈值

void SimulateKeyPress(WORD vkKey, bool press) {
    INPUT input = { 0 };
    input.type = INPUT_KEYBOARD;
    input.ki.wVk = vkKey;
    input.ki.dwFlags = press ? 0 : KEYEVENTF_KEYUP;
    SendInput(1, &input, sizeof(INPUT));
}

void Bhop() {
    auto& playerDataManager = PlayerDataManager::GetInstance();
    auto localPlayer = playerDataManager.GetLocalPlayerData();

    static auto client = reinterpret_cast<uintptr_t>(GetModuleHandle(L"client.dll"));
    if (!client || !all_settings::skin::movement::bunny_bhop || !localPlayer.pawn || localPlayer.health <= 0)
    {
        return;
    }

    // 获取视角角度
    auto viewAngles = reinterpret_cast<Vector3*>(client + cs2_dumper::offsets::client_dll::dwViewAngles);
    if (!viewAngles) {
        return;
    }

    // 初始化视角角度
    if (g_firstRun) {
        g_prevViewAngles = *viewAngles;
        g_firstRun = false;
        return;
    }

    // 计算yaw角度变化
    float yawDelta = viewAngles->y - g_prevViewAngles.y;

    // 处理角度环绕（-180到180的转换）
    if (yawDelta > 180.0f) yawDelta -= 360.0f;
    if (yawDelta < -180.0f) yawDelta += 360.0f;

    // 保存当前角度用于下一次比较
    g_prevViewAngles = *viewAngles;

    bool jump_hotkey = (GetAsyncKeyState(VK_SPACE) & 0x8000) != 0;
    static bool g_wasSpacePressed = false; // 跟踪空格键状态

    if (jump_hotkey) {
        g_wasSpacePressed = true;
        if (localPlayer.onground) {
            // 地面跳跃（保持不变）
            engine_client->execute_client_cmd("-jump;+jump;-jump");
        }
        else if (std::abs(yawDelta) > ANGLE_CHANGE_THRESHOLD && all_settings::skin::movement::auto_space_turn) {
            // 空中自动转向 - 模拟按下A和D键
            if (yawDelta > 0) {
                // 视角向右转动，按A键向左移动
                SimulateKeyPress('A', true);   // 按下A键
                SimulateKeyPress('D', false);  // 释放D键
            }
            else {
                // 视角向左转动，按D键向右移动
                SimulateKeyPress('D', true);   // 按下D键
                SimulateKeyPress('A', false);  // 释放A键
            }
        }
    }
    else {
        if (g_wasSpacePressed)
        {
            if (all_settings::skin::movement::auto_space_turn)
            {
                SimulateKeyPress('A', false);  // 释放A键
                SimulateKeyPress('D', false);  // 释放D键
            }
            g_firstRun = true;
            g_wasSpacePressed = false;
        }
    }
}

Draw_SkyBox g_draw_SkyBox;
// 全局实例
ThirdPersonManager thirdPersonManager;

void draw_SkyBox() {
    g_draw_SkyBox.Updateg_SkyBox();
}

// 原来的函数改为调用类的Update方法
void ToggleThirdPerson() {
    thirdPersonManager.Update(all_settings::visual::local::self::ThirdPerson.enabled);
}

void fast_stop() {
    auto& playerDataManager = PlayerDataManager::GetInstance();
    auto localPlayer = playerDataManager.GetLocalPlayerData();
    auto client = reinterpret_cast<uintptr_t>(GetModuleHandleA("client.dll"));
    if (!client || !all_settings::skin::movement::standalone_quick_stop || !localPlayer.pawn || localPlayer.health <= 0)
    {
        return;
    }

    // 静态变量跟踪按键状态
    static bool w_pressed = false;
    static bool s_pressed = false;
    static bool a_pressed = false;
    static bool d_pressed = false;

    bool forwardpressed = GetAsyncKeyState('W') & 0x8000;
    bool backpressed = GetAsyncKeyState('S') & 0x8000;
    bool leftpressed = GetAsyncKeyState('A') & 0x8000;
    bool rightpressed = GetAsyncKeyState('D') & 0x8000;

    // W键处理
    if (forwardpressed && !w_pressed) {
        w_pressed = true;
    }
    else if (!forwardpressed && w_pressed) {
        // 按键刚按下，执行+命令
        engine_client->execute_client_cmd("+back");
        std::this_thread::sleep_for(std::chrono::milliseconds(12)); // 5秒间隔
        engine_client->execute_client_cmd("-back");
        w_pressed = false;
    }

    // S键处理
    if (backpressed && !s_pressed) {
        s_pressed = true;
    }
    else if (!backpressed && s_pressed) {
        engine_client->execute_client_cmd("+forward");
        std::this_thread::sleep_for(std::chrono::milliseconds(12)); // 5秒间隔
        engine_client->execute_client_cmd("-forward");
        s_pressed = false;
    }

    // A键处理
    if (leftpressed && !a_pressed) {
        a_pressed = true;
    }
    else if (!leftpressed && a_pressed) {
        engine_client->execute_client_cmd("+right");
        std::this_thread::sleep_for(std::chrono::milliseconds(12)); // 5秒间隔
        engine_client->execute_client_cmd("-right");
        a_pressed = false;
    }

    // D键处理
    if (rightpressed && !d_pressed) {
        d_pressed = true;
    }
    else if (!rightpressed && d_pressed) {
        engine_client->execute_client_cmd("+left");
        std::this_thread::sleep_for(std::chrono::milliseconds(12)); // 5秒间隔
        engine_client->execute_client_cmd("-left");
        d_pressed = false;
    }
}